from decimal import Decimal
from rest_framework.generics import GenericAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection
from . import serializers

from goods.models import SKU


# 展示訂單結算
class OrderPlaceView(GenericAPIView):
    serializer_class = serializers.OrderPlaceSerializer
    permission_classes = [IsAuthenticated]


    def get(self,request):

        # 獲取redis中的需要結算的商品
        user = request.user
        redis_conn = get_redis_connection("cart")
        cart_dict = redis_conn.hgetall("cart_%s"%user.id)
        cart_selected_list = redis_conn.smembers("cart_selected_%s"%user.id)

        # 拼接數據
        sku_list = []
        for sku_id in cart_selected_list:
            sku = SKU.objects.get(id=sku_id)
            sku.count = int(cart_dict[sku_id])
            sku_list.append(sku)

        # 獲取序列化器
        serializer = self.get_serializer(instance=sku_list,many=True)

        # 返回響應
        contenxt = {
            "skus":serializer.data,
            "freight":Decimal(10.0)
        }
        return Response(contenxt)
        # return Response(data={"skus":serializer.data,"freight":Decimal(10.0)})

# 訂單提交
class OrderCommitView(CreateAPIView):
    serializer_class = serializers.OrderCommitSerializer
    permission_classes = [IsAuthenticated]



